<template>
  <div class="common-wrapper">
    <div class="common-search">
      <a-form layout="inline">
        <a-form-item label="部门">
          <a-tree-select
            multiple
            v-model="search.department_names"
            style="width: 150px;"
            :dropdown-style="{ maxHeight: '400px',  overflow: 'auto' }"
            placeholder="请选择部门"
            allow-clear
            :tree-default-expand-all="false"
            :treeData="departmentList"
            :replaceFields="{children:'childs', title:'dep_name', key:'pkey', value: 'pkey' }"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-model-item label="工种">
            <a-select v-model="search.work_type" mode="multiple" style="width: 185px">
              <a-select-option v-for="item in workList" :key="item.data_value">
                {{ item.data_name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        <a-form-item label="员工姓名">
          <a-input v-model="search.name" />
        </a-form-item>
        <a-form-item label="员工工号">
          <a-input v-model="search.id_card" />
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="getTableData(1)"> 搜索 </a-button>
      <!-- <a-button style="background: #13c2c2; border-color: #13c2c2; margin-left: 15px" type="primary" @click="showAuto(1)"> 自动排班 </a-button> -->
      <!-- <a-button style="background: #e6b422; border-color: #e6b422; margin-left: 15px" type="primary" @click="showAuto(2)"> 智能排班 </a-button> -->
      <a-button style="margin-left:15px;" type="primary" :disabled="!hasSelected" @click="openModel"> 批量排班 </a-button>
    </div>
    <div class="common-main" ref="main">
      <a-table
        size="middle"
        rowKey="pkey"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :columns="columns"
        :scroll="{ y: 300,x: 1200 }"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="openPlan(record.pkey)">排班计划</a-button>
        </template>
      </a-table>

      <a-table
        size="middle"
        rowKey="id"
        :columns="columns1"
        :scroll="{ y: 500,x: 1200 }"
        :data-source="userDataSource"
        bordered
        :pagination="userPagination"
        :loading="userLoading"
        @change="handleUserTableChange"
      >
        <template slot="week" slot-scope="text">
          <span>{{ '星期' + text }}</span>
        </template>
        <template slot="plan1" slot-scope="text, record">
          <span>{{ record.shift_period_time[0].enable ? '√' : '×' }}</span>
        </template>
        <template slot="type1" slot-scope="text, record">
          <span>{{ record.shift_period_time[0].type_name }}</span>
        </template>
        <template slot="start1" slot-scope="text, record">
          <span>{{ record.shift_period_time[0].work_time }}</span>
        </template>
        <template slot="end1" slot-scope="text, record">
          <span>{{ record.shift_period_time[0].after_time }}</span>
        </template>
        <template slot="plan2" slot-scope="text, record">
          <span>{{ record.shift_period_time[1].enable ? '√' : '×' }}</span>
        </template>
        <template slot="type2" slot-scope="text, record">
          <span>{{ record.shift_period_time[1].type_name }}</span>
        </template>
        <template slot="start2" slot-scope="text, record">
          <span>{{ record.shift_period_time[1].work_time }}</span>
        </template>
        <template slot="end2" slot-scope="text, record">
          <span>{{ record.shift_period_time[1].after_time }}</span>
        </template>
        <template slot="plan3" slot-scope="text, record">
          <span>{{ record.shift_period_time[2].enable ? '√' : '×' }}</span>
        </template>
        <template slot="type3" slot-scope="text, record">
          <span>{{ record.shift_period_time[2].type_name }}</span>
        </template>
        <template slot="start3" slot-scope="text, record">
          <span>{{ record.shift_period_time[2].work_time }}</span>
        </template>
        <template slot="end3" slot-scope="text, record">
          <span>{{ record.shift_period_time[2].after_time }}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="openChangePlan(record)">修改班次</a-button>
        </template>
      </a-table>
    </div>
    <!-- 修改排班 -->
    <a-modal title="设置班制" :visible="visible" @cancel="handleCancel" width="45%">
      <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="选择日期段" prop="date">
          <a-range-picker @change="onDateChange" style="width: 300px" />
        </a-form-model-item>
        <a-form-model-item label="选择班制" required>
          <a-button type="primary" :disabled="!hasSelectedDate" @click="openModelPlan">
            批量设置班制
          </a-button>
          <a-table
            :row-selection="{ selectedRowKeys: selectedDateRowKeys, onChange: onSelectDateChange }"
            :columns="planColumns"
            :pagination="false"
            :data-source="subParams.plans"
            size="small"
            :scroll="{ y: 500 }"
            :rowKey="(record) => record.plan_date"
          >
            <template slot="week" slot-scope="text, record">
              <span>{{ record.plan_date | weekFilter }}</span>
            </template>
            <template slot="class" slot-scope="text, record">
              <a-select style="width:180px;" v-model="record.class_key">
                <a-select-option v-for="(item, key) of planList" :key="key" :value="key">
                  {{ item }}
                </a-select-option>
              </a-select>
            </template>
          </a-table>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="btnLoading" @click="submitPlanAll">生成排班表</a-button>
      </template>
    </a-modal>
    <!-- 修改排班 -->
    <a-modal title="设置班制" :visible="visibleClass" @cancel="handleCancelClass">
      <span>选择班制：</span>
      <a-select v-model="class_key" style="width: 400px;margin:20px auto;">
        <a-select-option v-for="(item, key) of planList" :key="key" :value="key">
          {{ item }}
        </a-select-option>
      </a-select>
      <template slot="footer">
        <a-button @click="handleCancelClass">取消</a-button>
        <a-button type="primary" @click="submitClass">确定</a-button>
      </template>
    </a-modal>

    <!-- 自动排班 -->
    <a-modal :title="autoTitle" :visible="autoVisible" @cancel="autoVisible = !autoVisible" :width="600">
      <a-form layout="inline" :form="form1">
        <a-form-item label="从" style="margin-bottom:0;">
          <a-form-item
            :style="{ display: 'inline-block', width: 'calc(48% - 42px)' }"
          >
            <a-month-picker
              name="for_month"
              placeholder="请选择已排班月份"
              v-decorator="[
                'for_month',
                {
                  rules: [{ required: true, message: '请选择已排班月份' }]
                },
              ]" />
          </a-form-item>
          <span :style="{ display: 'inline-block', width: '44px', textAlign: 'center' ,marginRight:'10px'}">
            排至
          </span>
          <a-form-item :style="{ display: 'inline-block', width: 'calc(48% - 42px)' }">
            <a-month-picker
              name="to_month"
              placeholder="请选择需要排班月份"
              v-decorator="[
                'to_month',
                {
                  rules: [{ required: true, message: '请选择需要排班月份' }],
                  initialValue: moment(),
                },
              ]" />
          </a-form-item>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="autoVisible = false">取消</a-button>
        <a-button type="primary" :loading="confirmLoading" @click="handleSubmit">生成排班表</a-button>
      </template>
    </a-modal>

    <!-- 智能排班 -->
    <a-modal :title="autoTitle" :visible="autoVisible1" @cancel="autoVisible1 = !autoVisible1" :width="600">
      <a-form layout="inline" :form="form1">
        <a-form-item label="从" style="margin-bottom:0;">
          <a-form-item
            :style="{ display: 'inline-block', width: 'calc(48% - 42px)' }"
          >
            <a-date-picker
              name="for_month"
              placeholder="已排班日期"
              v-decorator="[
                'for_month',
                {
                  rules: [{ required: true, message: '请选择已排班日期' }]
                },
              ]" />
          </a-form-item>
          <span :style="{ display: 'inline-block', width: '44px', textAlign: 'center' ,marginRight:'10px'}">
            排到
          </span>
          <a-form-item :style="{ display: 'inline-block', width: 'calc(48% - 42px)' }">
            <a-date-picker
              name="to_month"
              placeholder="需要排班日期"
              v-decorator="[
                'to_month',
                {
                  rules: [{ required: true, message: '请选择需要排班日期' }],
                  initialValue: moment(),
                },
              ]" />
          </a-form-item>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="autoVisible = false">取消</a-button>
        <a-button type="primary" :loading="confirmLoading" @click="handleSubmit1">生成排班表</a-button>
      </template>
    </a-modal>

    <!-- 修改排班 -->
    <a-modal title="修改排班" :visible="visiblePlan" @cancel="handleCancelPlan">
      <a-form-model ref="planForm" :model="planForm">
        <a-form-model-item label="选择班次" :colon="false">
          <a-select v-model="planForm.class_key" @change="handleSelect">
            <a-select-option v-for="(item, key) of planList" :key="key" :value="key">
              {{key}}-{{ item }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="handleCancelPlan">取消</a-button>
        <a-button type="primary" @click="submitPlan">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment';
import { getUsersList } from '@/api/user'
import { getAllDate } from '@/utils/util'
import { getClassSelect, batchsetplan, getDepartmentList, autoSetPlan,getPlan, changePlan,getDatadictionary } from '@/api/plan'
export default {
  data () {
    const columns = [
      {
        title: '员工姓名',
        dataIndex: 'person_name',
        align: 'center'
      },
      {
        title: '员工工号',
        dataIndex: 'person_idcard',
        align: 'center'
      },
      {
        title: '工种',
        dataIndex: 'work_type_name',
        align: 'center'
      },
      {
        title: '部门名称',
        dataIndex: 'dep_name',
        align: 'center'
      },
      {
        title: '入职时间',
        dataIndex: 'person_come_date',
        align: 'center'
      },
      {
        title: '员工性别',
        dataIndex: 'person_sex',
        align: 'center'
      },
      // {
      //   title: '员工手机号',
      //   dataIndex: 'person_phone',
      //   align: 'center'
      // },
      {
        title: '排班',
        width: 120,
        align: 'center',
        scopedSlots: { customRender: 'action' }
      }
    ]
    const columns1 = [
      {
        title: '计划日期',
        dataIndex: 'plan_date',
        align: 'center'
      },
      {
        title: '星期',
        dataIndex: 'week',
        align: 'center',
        scopedSlots: { customRender: 'week' }
      },
      {
        title: '班次名称',
        dataIndex: 'shift_name',
        align: 'center'
      },
      {
        title: '【启用-1',
        align: 'center',
        scopedSlots: { customRender: 'plan1' }
      },
      {
        title: '类型-1',
        align: 'center',
        scopedSlots: { customRender: 'type1' }
      },
      {
        title: '上班-1',
        align: 'center',
        scopedSlots: { customRender: 'start1' }
      },
      {
        title: '下班-1】',
        align: 'center',
        scopedSlots: { customRender: 'end1' }
      },
      {
        title: '【启用-2',
        align: 'center',
        scopedSlots: { customRender: 'plan2' }
      },
      {
        title: '类型-2',
        align: 'center',
        scopedSlots: { customRender: 'type2' }
      },
      {
        title: '上班-2',
        align: 'center',
        scopedSlots: { customRender: 'start2' }
      },
      {
        title: '下班-2】',
        align: 'center',
        scopedSlots: { customRender: 'end2' }
      },
      {
        title: '【启用-3',
        align: 'center',
        scopedSlots: { customRender: 'plan3' }
      },
      {
        title: '类型-3',
        align: 'center',
        scopedSlots: { customRender: 'type3' }
      },
      {
        title: '上班-3',
        align: 'center',
        scopedSlots: { customRender: 'start3' }
      },
      {
        title: '下班-3】',
        align: 'center',
        scopedSlots: { customRender: 'end3' }
      },
      {
        title: '操作',
        width: 120,
        align: 'center',
        scopedSlots: { customRender: 'action' }
      }
    ]
    return {
      autoTitle: '自动排班',
      autoType: 1, // 1自动排班 2 只能排班
      autoVisible: false,
      autoVisible1: false,
      search: {
        name: '',
        id_card: '',
        department_names: [],
        work_type: [],
        page_index: 1,
        page_size: 20
      },
      labelCol: { span: 3 },
      wrapperCol: { span: 20 },
      form: {
        date: null
      },
      rules: {
         date: [{ required: true, message: '请选择日期段', trigger: 'blur' }]
      },
      subParams: {
        person_ids: [],
        plans: []
      },
      columns,
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        },
        pageSizeOptions: ['10', '20', '30', '40', '50','100','500','1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      loading: false,
      dataSource: [],
      columns1,
      /* 分页参数 */
      userPagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        },
        pageSizeOptions: ['10', '20', '30', '40', '50','100','500','1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      userLoading: false,
      userDataSource: [],
      departmentList: [],
      selectedRowKeys: [],
      selectedRows: [],
      selectedDateRowKeys: [],
      selectedDateRows: [],
      visible: false,
      visibleClass: false,
      planList: [],
      planColumns: [
        {
          dataIndex: 'plan_date',
          align: 'center',
          title: '日期'
        },
        {
          title: '星期',
          align: 'center',
          scopedSlots: { customRender: 'week' }
        },
        {
          title: '班制名称',
          align: 'center',
          scopedSlots: { customRender: 'class' }
        }
      ],
      class_key: '',
      btnLoading: false,
      form1: this.$form.createForm(this),
      confirmLoading: false,

      planForm: {
        code: '',
        class_key: ''
      },
      planSearch: {
        page_index: 1,
        page_size: 20,
        person_id: ''
      },
       // 工种列表
       workList: [],
      visiblePlan: false,
    }
  },
  filters: {
    weekFilter (value) {
      var dateArray = value.split("-");
      var date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
      return "日一二三四五六".charAt(date.getDay());
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0;
    },
    hasSelectedDate () {
      return this.selectedDateRowKeys.length > 0;
    }
  },
  mounted () {
    this.resize()
    this.getWorkList()
    this.getDepartmentList()
    this.getPlanList()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    moment,
    // 自动 智能排班
    showAuto (type) {
      if (type === 1) {
        this.autoTitle = '自动排班'
        this.autoVisible = true
      } else {
        this.autoTitle = '智能排班'
        this.autoVisible1 = true
      }
      this.autoType = type
    },
    disabledDate (current) {
      // Can not select days before today and today
      return current && current >= moment().add(-1, 'months');
    },
    disabledDateEnd (current) {
      // Can not select days before today and today
      return current && current >= moment().add(-1, 'months');
    },
    async resize () {
      // this.getPageSize()
      await this.getTableData()
      // this.getUserTableData()
    },
    // 获取部门列表
    async getDepartmentList () {
      const { data } = await getDepartmentList()
      this.departmentList = data
    },
    // 获取工种列表
    async getWorkList() {
      const { data } = await getDatadictionary({ data_type: 3 })
      this.workList = data
    },
    // 获取班次下拉框
    async getPlanList () {
      const { data } = await getClassSelect()
      this.planList = data
    },
    // 获取表格
    async getTableData (cur) {
      this.resetTable()
      this.loading = true
      if (cur === 1) {
        this.search.page_index = cur
        this.pagination.current = cur
      } else {
        this.search.page_index = this.pagination.current
      }
      this.search.page_size = this.pagination.pageSize
      let work_types = this.search.work_type.join(',')
      let department_names = this.search.department_names.join(',')
      const { data } = await getUsersList({
        ...this.search,
        work_types,
        department_names
      })
      this.dataSource = data.items
      this.pagination.total = data.totalCount
      this.loading = false
    },
    getPageSize () {
      const height = this.$refs.main.offsetHeight - 68 - 30
      const pageSize = Math.floor(height / 50)
      this.search.page_size = pageSize
      this.pagination.pageSize = pageSize
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.getTableData()
    },
    openPlan (id) { 
      // this.$router.push({
      //   path: '/plan/planList',
      //   query: { person_id: id }
      // })
      this.planSearch.person_id = id
      this.getUserTableData()
    },
    // 选择员工
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      const selectArr = []
      selectedRows.forEach(item => {
        selectArr.push(item.pkey)
      });
      console.log(selectArr)
      this.subParams.person_ids = selectArr
    },
    openModel () {
      this.visible = true
    },
    handleCancel () {
      this.resetTable()
      this.visible = false
    },
    resetTable () {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.subParams.plans = []
      this.subParams.person_ids = []
      this.form.date = []
      this.class_key = ''
      this.selectedDateRowKeys = [];
      this.selectedDateRows = [];
    },
    submitPlanAll () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          for (let index = 0; index < this.subParams.plans.length; index++) {
            if (this.subParams.plans[index].class_key === '') {
              this.$message.error('请设置班制！')
              return
            }
          }
          this.btnLoading = true
          const { succeeded } = await batchsetplan(this.subParams)
          if (succeeded) {
            this.$message.success('操作成功！')
            this.visible = false
            this.getUserTableData()
            this.btnLoading = false
          } else {
            this.$message.error('操作失败！')
            this.btnLoading = false
          }
        } else {
          return false;
        }
      });
    },
    // 选择日期段
    onDateChange (date, dateString) {
      this.form.date = date
      this.subParams.plans = getAllDate(dateString[0], dateString[1])
    },
    onSelectDateChange (selectedRowKeys, selectedRows) {
      this.selectedDateRowKeys = selectedRowKeys;
      this.selectedDateRows = selectedRows;
    },
    openModelPlan () {
      this.visibleClass = true
    },
    handleCancelClass () {
      this.class_key = ''
      this.selectedDateRowKeys = [];
      this.selectedDateRows = [];
      this.visibleClass = false
    },
    submitClass () {
      this.subParams.plans.forEach(item => {
        this.selectedDateRows.forEach(item1 => {
          if (item1.plan_date === item.plan_date) {
            item.class_key = this.class_key
          }
        })
      })
      this.selectedDateRows = [];
      this.class_key = ''
      this.selectedDateRowKeys = [];
      this.visibleClass = false
    },
    handleSubmit (e) {
       const self = this
      self.form1.validateFields((errors, values) => {
        console.log(values);
        if (!errors) {
          self.confirmLoading = true
          const data = Object.assign({}, values)
          if (values.for_month) {
            const date = values.for_month.format('YYYY-MM-01')
            data.for_month = date
          }
          if (values.to_month) {
            const date = values.to_month.format('YYYY-MM-01')
            data.to_month = date
          }
          console.log(data);
          let cmd = 'AutoSetPlan'
          if (this.autoType === 2) cmd = 'ConjectureSetPlan'
          autoSetPlan(cmd, data).then(res => {
              if (res.succeeded) {
                this.$message.success('排班成功')
                this.autoVisible = false
              } else {
                this.$message.error(res.errors)
              }
              self.confirmLoading = false
          }).catch(() => {
             self.confirmLoading = false
          })
        }
      })
    },
    handleSubmit1 (e) {
       const self = this
      self.form1.validateFields((errors, values) => {
        console.log(values);
        if (!errors) {
          self.confirmLoading = true
          const data = Object.assign({}, values)
          if (values.for_month) {
            const date = values.for_month.format('YYYY-MM-DD')
            data.for_month = date
          }
          if (values.to_month) {
            const date = values.to_month.format('YYYY-MM-DD')
            data.to_month = date
          }
          console.log(data);
          const cmd = 'ConjectureSetPlan'
          autoSetPlan(cmd, data).then(res => {
              if (res.succeeded) {
                this.$message.success('排班成功')
                this.autoVisible1 = false
              } else {
                this.$message.error(res.errors)
              }
              self.confirmLoading = false
          }).catch(() => {
             self.confirmLoading = false
          })
        }
      })
    },

    // 修改排班
    openChangePlan (item) {
      this.planForm.code = item.code
      this.visiblePlan = true
    },
    handleCancelPlan () {
      this.planForm.code = ''
      this.planForm.class_key = ''
      this.visiblePlan = false
      this.$refs.planForm.resetFields()
    },
    handleSelect (value) {
      this.planForm.class_key = value
    },
    async submitPlan () {
      const { succeeded } = await changePlan(this.planForm)
      if (succeeded) {
        this.resize()
        this.$message.success('修改成功，请重新处理考勤数据！')
      } else {
         this.$message.error('操作失败！')
      }
      this.planForm.code = ''
      this.planForm.class_key = ''
      this.$refs.planForm.resetFields()
      this.visiblePlan = false
    },
    // 获取表格
    async getUserTableData (cur) {
      this.userLoading = true
      if (cur === 1) {
        this.planSearch.page_index = cur
        this.pagination.current = cur
      } else {
        this.planSearch.page_index = this.userPagination.current
      }
      this.planSearch.page_size = this.userPagination.pageSize
      const { data } = await getPlan(this.planSearch)
      this.userDataSource = data.items
      this.userPagination.total = data.totalCount
      this.userLoading = false
    },
    handleUserTableChange (pagination, filters, sorter) {
      this.userPagination = pagination
      this.getUserTableData()
    }
  }
}
</script>

<style lang="less">
.common-wrapper {
  height: 100%;
  padding: 20px;
}
.common-search {
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #efefef;
}
.common-main {
  height: calc(100% - 50px);
  padding-top: 10px;
  .ant-table .ant-btn {
    height: 24px;
    line-height: 24px;
  }
}
</style>
